var gamejs = require('gamejs');
var turretjs = require("js/turret");

/**
 * Create a Turret object
 *
 * @param {Match} match The match where this object will work
 * @param {[number, number]} coords The radar's position, in format [x, y]
 */
var laserTurret = exports.laserTurret = function(match, coords) {
	laserTurret.superConstructor.apply(this, arguments);
	this.currentMatch = match;
	this.center = coords;
	this.target = [10, 10]; // coordinates locked target
	this.startHealth = this.health = 1000;
	this.level = 0;
	this.upgradeList = [
		{ price: 20, radius: 300, damage: 0.3, resaleValue: 15 }, // livello 0
		{ price: 15, radius: 400, damage: .7, resaleValue: 25 }, // livello 1
		{ price: 15, radius: 500, damage: 1.2, resaleValue: 35 }  // livello 2
	];
	this.radius = this.upgradeList[this.level].radius;
	this.currentRadius = this.radius;
	this.image = gamejs.image.load(config.dir.images + "turret.png");
};

/**
 * laserTurret extends Turret
 */
gamejs.utils.objects.extend(laserTurret, turretjs.Turret);

/**
 * Updates the position of the detector ray of the turret.
 *
 * @param {number} msDuration The time past from the last call, in milliseconds
 */
laserTurret.prototype.update = function(msDuration) {
	var target;
	var detected = false;
	var distance;
	var center = this.center;
	var radius = this.radius;
	var damage = this.upgradeList[this.level].damage;
	this.currentMatch.getMap().getEnemies().sprites().forEach(function(enemy) {
		if (enemy.isDetected() && ! detected) {
			//check if the enemy is in the turret radius
			if(gamejs.utils.vectors.distance(center, enemy.getCoordinates()) < radius){
				enemy.hit( damage );
				detected = true;
				target = enemy;
			};
		};
	});
	
	this.target = target;
};

/**
 * Draws the turret in the given Surface
 *
 * @param {gamejs.Surface} surface The Surface where draw on
 */
laserTurret.prototype.draw = function(surface) {
	//draw turret tower
	var dim = this.image.getSize();
	var upLeft = gamejs.utils.vectors.subtract(this.center, gamejs.utils.vectors.divide(dim, 2));
	surface.blit(this.image, upLeft);

	//healt bar
	var startLine = gamejs.utils.vectors.subtract(this.center, gamejs.utils.vectors.divide([dim[0], dim[1] *3/2], 2));
	var endLine = gamejs.utils.vectors.add(startLine, [dim[0] *  this.health /this.startHealth, 0]);
	gamejs.draw.line(surface, '#adff2f', startLine, endLine, 2);
	
	//draw laser
	if(this.target) {
		gamejs.draw.line(surface, '#ff0000', this.center, this.target.getCoordinates(), 0.5);
	}
};